package aquarium.reseau;

import java.io.*;
import java.net.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import aquarium.gui.*;
import aquarium.items.AquariumItem;
import aquarium.items.Stone;

public class ServeurTCP extends Thread {

	private int _port;
	private ServerSocket _serverSocket;
	private HashMap<Integer, Vector<String>> _list_packet_aquarium_items = new HashMap<Integer, Vector<String>>();
	private Vector<Connection> _list_connection = new Vector<Connection>();
	private int _nb_Socket = 0; // Correspond aussi a l'id du Socket

	private String[] _items_base; 

	private Aquarium _aquarium;
	private Animation _animation;
	private UpdateCollection _up;

	
	public void start(int port){
		this._port = port;
		
		this.start();
	}

	public void run(){

		//_port = 9999;

		aquarium_init();
		accept_all_connection();

	}

	/**** Fonctions ****/

	private void aquarium_init(){
		_aquarium = new Aquarium(); // On lance l'aquarium seul
		_animation = new Animation(_aquarium);
		_aquarium.randomStoneAndSeaweedGenerator(_aquarium.getCollection());
		_items_base = creatPackageTCP(_aquarium);
		Windows _windows = new Windows();
		_windows.start(_animation);
		_up = new UpdateCollection();
		_up.start(_list_packet_aquarium_items, _list_connection, _aquarium);
	}       	


	private void accept_all_connection(){
		try{

			_serverSocket = new ServerSocket(_port);

			Socket socket;
			Connection connect;
			while (true) {
				socket = _serverSocket.accept();
				connect = new Connection();
				connect.start(socket, _items_base, _nb_Socket);
				synchronized(_list_connection){
					_list_connection.add(connect);
				}
				_nb_Socket++;

			}
		}catch (IOException e) {
			System.out.println("Erreur a la creation de Socket : " + e.getMessage());
			System.exit(1);
		}
	}


	public String[] creatPackageTCP(Aquarium _aquarium){
		Collection<AquariumItem> items = _aquarium.getCollection();
		String [] elements = new String[items.size()+1];
		String description = null;
		int i = 0;
		Iterator<AquariumItem> it = items.iterator();
		while (it.hasNext()) 
		{
			AquariumItem ai = it.next();
			if(ai instanceof Stone)
				description = new String("m ");
			else
				description = new String("s ");

			description = description.concat(String.valueOf(ai.get_position().x)).concat(" ");
			description = description.concat(String.valueOf(ai.get_position().y)).concat(" ");
			description = description.concat(String.valueOf(ai.get_size()).concat(" "));
			description = description.concat(String.valueOf(ai.get_adult_size()).concat(" "));
			description = description.concat(String.valueOf(-1).concat(" "));
			description = description.concat(String.valueOf(-1).concat(" "));
			description = description.concat(String.valueOf("n"));

			elements[i] = new String(description);
			i++;
		}
		elements[i] = new String("end").concat(" 0");
		return elements;
	}
}

